package com.puhui.lib.base

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.puhui.lib.base.dialog.LoadingDialog
import com.puhui.lib.base.mvp.IView
import com.puhui.lib.utils.ToastUtil
import com.trello.rxlifecycle3.components.support.RxFragment
import org.greenrobot.eventbus.EventBus

abstract class BaseFragment<T : ViewDataBinding> : RxFragment(), IView {

    open lateinit var mContentView: T
    private var mLoadingDialog: LoadingDialog? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
//        return inflater.inflate(getLayoutId(), container, false)
        mContentView = DataBindingUtil.inflate(inflater, getLayoutId(), container, false)
        return mContentView.root
    }

    @LayoutRes
    abstract fun getLayoutId(): Int

    /**
     * 先于onActivityCreated执行
     */
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (needEventNotify() && !EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initView(savedInstanceState)
    }

    abstract fun initView(savedInstanceState: Bundle?)

    open fun needEventNotify(): Boolean = false

    override fun startLoading(text: String?) {
        mLoadingDialog?.let {
            if (!it.isVisible) it.show(this)
        }
    }

    override fun stopLoading() {
        mLoadingDialog?.let {
            if (it.isVisible) it.dismiss()
        }
    }

    override fun showToast(message: String?) {
        ToastUtil.showToast(message)
    }

    override fun showToast(resourceId: Int) {
        ToastUtil.showToast(getString(resourceId))
    }

    override fun getTopContext(): Context {
        context?.let { return it }
        return super.getTopContext()
    }

    override fun getTopActivity(): Activity {
        activity?.let { return it }
        return super.getTopActivity()
    }

    override fun startActivity(clazz: Class<*>) {
        activity?.startActivity(Intent(activity, clazz))
    }

    override fun startActivityForResult(clazz: Class<*>, requestCode: Int) {
        activity?.startActivityForResult(Intent(activity, clazz), requestCode)
    }

    override fun isAvailable(): Boolean {
        return isVisible
    }
}